363C - Fixing Typos - CodeForces Solution


greedy implementation *1400

Please click on ads to support us..

Python Code:

import sys
from bisect import bisect_right, bisect_left
import os
import sys
from io import BytesIO, IOBase
from math import factorial, floor, sqrt, inf, ceil, gcd
from collections import defaultdict, deque

BUFSIZE = 8192
 
class FastIO(IOBase):
    newlines = 0
 
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
 
 
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
 
 
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(s[:len(s) - 1])
def invr():
    return(map(int,input().split()))
def insr2():
    s = input()
    return(s.split(" "))


def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i and i != 1:
                divisors.append(n // i)
    return divisors

def dfs(graph, vertex):
    visited = set()
    tree = []
    deq = deque([vertex])
    while deq:
        vertex = deq.pop()
        if vertex not in visited:
            visited.add(vertex)
            deq.extend(graph[vertex])
            tree.append(vertex)
    return tree

def find_in_sorted_list(elem, sorted_list):
        'Locate the leftmost value exactly equal to x'
    i = bisect_left(sorted_list, elem)
    if i != len(sorted_list) and sorted_list[i] == elem:
        return i
    return -1


class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a+b):
        
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()
 
        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])
 
    def __delitem__(self, idx):
        self[idx] = self._default
 
    def __getitem__(self, idx):
        return self.data[idx + self._size]
 
    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1
 
    def __len__(self):
        return self._len
 
    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        start += self._size
        stop += self._size
 
        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res
 
    def __repr__(self):
        return "SegmentTree({0})".format(self.data)



s = input().strip()
n = len(s)
i = 1


cur_last = 0
cur = 1
last_letter = s[0]
ans = [s[0]]
while i < n:
    if s[i] == last_letter:
        if cur == 2:
            i += 1
            continue
        elif cur == 1:
            if cur_last == 2:
                i += 1
                continue
            else:
                cur += 1
                ans.append(s[i])
        else:
            cur += 1
            ans.append(s[i])
    else:
        cur_last = cur
        cur = 1
        ans.append(s[i])
        last_letter = s[i]
    
    i += 1
    
print(''.join([str(a) for a in ans]))

C++ Code:

#include<bits/stdc++.h>
#define ll long long
#define endl "\n"
const int mod=1e9 + 7;
using namespace std;

ll factor(ll n)
{
    ll num=0;
    for(ll i=1;i*i<=n;i++)
    {
        if(n%i==0)
        {
            num++;
            if((n/i)!=i)
                num++;
        }
    }
    return num;
}

ll prime_factors(ll n)
{
    ll ret = 0;
    if(n%2 == 0)    ret++;  
    while (n%2 == 0)
        n = n/2;

    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        if(n%i == 0)    ret++;
        while (n%i == 0)
        {
            n = n/i;
        }
    }

    return ret;
}

bool isPrime(int n)
{
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
    if (n % 2 == 0 || n % 3 == 0)
        return false;
     
    for (int i = 5; i * i <= n; i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
  
    return true;
}

int main()
{
    #ifndef ONLINE_JUDGE
    //input from input.txt
        freopen("input.txt", "r", stdin);
    //output on output.txt
        freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    //always use () when working with unary operators. ALWAYS
    //use (ll) when using .length() or .size()
    //you can sort 2D vectors lexicographically
    // You can do it and you will do it
    //sum of cubes, ribbon cut(find numbers, not brute)
    /*operands must be of the same data type in max,min
      so use typecasting*/
    //use typecasting to ll when using pow, log
    //Be patient even if the question is easy
    //Look at the conditions properly, they often tell you a lot of things. Sometimes they tell you the answer directly.
    //Brother of mine, always use ll. Always
    //My dear brother, please use ll. Please. Just please.
    
    string s;
    cin>>s;
    vector<pair<char, int>> v;
    char prev = s[0];
    int c = 1;
    for(int i = 1;i<s.length();i++)
    {
        if(s[i] != s[i-1])
        {
            v.push_back({prev, c});
            prev = s[i];
            c = 1;
        }
        else
            c++;
    }
    v.push_back({prev, c});
    string ans = "";
    for(int i = 0;i<min(v[0].second, 2);i++)
        ans.push_back(v[0].first);
    c = min(v[0].second, 2);
    for(int i = 1;i<v.size();i++)
    {
        if(c == 1)
        {
            for(int j = 0;j<min(v[i].second, 2);j++)
                ans.push_back(v[i].first);
            c = min(v[i].second, 2);
        }
        else if(c == 2)
        {
            for(int j = 0;j<1;j++)
                ans.push_back(v[i].first);
            c = 1;
        }
    }
    cout<<ans<<endl;
    return 0;
}


Comments

Submit
0 Comments
More Questions

1366A - Shovels and Swords
919A - Supermarket
630C - Lucky Numbers
1208B - Uniqueness
1384A - Common Prefixes
371A - K-Periodic Array
1542A - Odd Set
1567B - MEXor Mixup
669A - Little Artem and Presents
691B - s-palindrome
851A - Arpa and a research in Mexican wave
811A - Vladik and Courtesy
1006B - Polycarp's Practice
1422A - Fence
21D - Traveling Graph
1559B - Mocha and Red and Blue
1579C - Ticks
268B - Buttons
898A - Rounding
1372B - Omkar and Last Class of Math
1025D - Recovering BST
439A - Devu the Singer and Churu the Joker
1323A - Even Subset Sum Problem
1095A - Repeating Cipher
630F - Selection of Personnel
630K - Indivisibility
20B - Equation
600B - Queries about less or equal elements
1015A - Points in Segments
1593B - Make it Divisible by 25